<template>
  <div class="person-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="工号">
        <el-input v-model="searchForm.personId" placeholder="请输入工号" clearable />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="searchForm.personName" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="searchForm.department" placeholder="请选择部门" clearable>
          <el-option label="表面处理车间" value="表面处理车间" />
          <el-option label="锻压车间" value="锻压车间" />
          <el-option label="组装车间" value="组装车间" />
          <el-option label="质检车间" value="质检车间" />
          <el-option label="机加车间" value="机加车间" />
        </el-select>
      </el-form-item>
      <el-form-item label="入职时间">
        <el-date-picker
          v-model="searchForm.hireDateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="showAddDialog = true">添加人员</el-button>
      </el-form-item>
    </el-form>

    <!-- 人员列表 -->
    <el-table :data="personList" border>
      <el-table-column prop="personId" label="工号" min-width="100" />
      <el-table-column prop="personName" label="姓名" min-width="120" />
      <el-table-column prop="department" label="部门" min-width="120" />
      <el-table-column prop="hireDate" label="入职时间" min-width="140" :formatter="formatDate" />
      <el-table-column prop="education" label="学历" min-width="100" />
      <el-table-column prop="major" label="专业" min-width="120" />
      <el-table-column prop="title" label="职称" min-width="120" />
      <el-table-column prop="phone" label="手机号" min-width="140">
        <template #default="{ row }">{{ row.phone || '-' }}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="220">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEditPerson(row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDeletePerson(row.personId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination

      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 添加人员对话框 -->
    <el-dialog :title="editPersonId ? '修改人员' : '添加人员'" v-model="showAddDialog">
      <el-form :model="addForm" label-width="100px" :rules="formRules">
        <el-form-item label="姓名" prop="personName">
          <el-input v-model="addForm.personName" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="addForm.department" placeholder="请选择部门">
            <el-option label="表面处理车间" value="表面处理车间" />
            <el-option label="锻压车间" value="锻压车间" />
            <el-option label="组装车间" value="组装车间" />
            <el-option label="质检车间" value="质检车间" />
            <el-option label="机加车间" value="机加车间" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" prop="hireDate">
          <el-date-picker
            v-model="addForm.hireDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="学历">
          <el-input v-model="addForm.education" />
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="addForm.major" />
        </el-form-item>
        <el-form-item label="职称">
          <el-input v-model="addForm.title" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入11位手机号" />
        </el-form-item>
        <el-form-item label="家庭住址">
          <el-input v-model="addForm.address" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input v-model="addForm.profile" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editPersonId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmitPerson">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';

const searchForm = reactive({
  personId: '',
  personName: '',
  department: '',
  hireDateRange: [],
})

const addForm = reactive({
  personName: '',
  department: '',
  hireDate: '',
  education: '',
  major: '',
  title: '',
  phone: '',
  address: '',
  profile: ''
})

const formRules = reactive({
  personName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

const personList = ref([])
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})
const showAddDialog = ref(false)
const editPersonId = ref<number | null>(null)

const formatDate = (row: any) => {
  return row.hireDate ? new Date(row.hireDate).toISOString().split('T')[0] : ''
}

const fetchPersons = async (pageNum = 1) => {
  try {
    const params = {
      personId: searchForm.personId || null,
      personName: searchForm.personName || null,
      department: searchForm.department || null,
      hireBeginDate: searchForm.hireDateRange?.[0] || null,
      hireEndDate: searchForm.hireDateRange?.[1] || null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `person/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    personList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    ElMessage.error('获取人员数据失败')
  }
}

const handleEditPerson = (row: any) => {
  Object.assign(addForm, row)
  editPersonId.value = row.personId
  showAddDialog.value = true
}

const handleDeletePerson = async (personId: number) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `person/${personId}`)
    ElMessage.success('删除成功')
    fetchPersons(1)
  } catch (e) {
    ElMessage.error('删除失败')
  }
}

const handleSubmitPerson = async () => {
  try {
    const url = editPersonId.value
      ? import.meta.env.VITE_API_URL + 'person/update'
      : import.meta.env.VITE_API_URL + 'person/save'

    await axios.post(url, {
      ...addForm,
      personId: editPersonId.value
    })

    ElMessage.success(editPersonId.value ? '修改成功' : '添加成功')
    showAddDialog.value = false
    editPersonId.value = null
    await fetchPersons(1)
  } catch (e) {
    ElMessage.error(editPersonId.value ? '修改失败' : '添加失败')
  }
}

const handleSearch = () => fetchPersons(1)
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  fetchPersons(1)
}
const handlePageChange = (page: number) => fetchPersons(page)

onMounted(() => {
  fetchPersons(1)
})
</script>

<style scoped>
@import '@/styles/views.css';
</style>
